package com.mflex.flexwi;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

import androidx.collection.SimpleArrayMap;

import com.dou361.dialogui.DialogUIUtils;
import com.king.zxing.CameraScan;
import com.mflex.flexwi.util.CommonUtil;
import com.mflex.flexwi.util.WebServiceUtil;
import com.rosefinches.smiledialog.SmileDialog;
import com.rosefinches.smiledialog.SmileDialogBuilder;
import com.rosefinches.smiledialog.enums.SmileDialogType;

import org.apache.commons.lang3.StringUtils;

public class PdfDetailActive extends BaseActivity {
//    private TextView txtPDFtitle;
    private Button btnPDFclosed;
    private EditText txtEmployeeNo;
    private EditText txtLeaderNo;
    private Button btnSign;
    private Button btnSerach;
    private WebView wvPDF;

    private ImageButton imageButtonEmployeeNo;
    private ImageButton imageButtonLeaderNo;


    private static String  pdfUrlBase;
    private static String pdfUrl;
    private static String webServiceUrl;
    private static String pdfTile;
    private static String docName;
    private static String docNumber;
    private static String docVersion;

    public final int REQUEST_CODE_EMPLOYEE_NO = 1;
    public final int REQUEST_CODE_LEADER_NO = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(CommonUtil.isTabletDevice(this)){
            setContentView(R.layout.activity_pdf_detail_pad);
            imageButtonEmployeeNo = (ImageButton) findViewById(R.id.imageButtonEmployeeNo);
            imageButtonLeaderNo = (ImageButton) findViewById(R.id.imageButtonLeaderNo);

            imageButtonEmployeeNo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent=new Intent(PdfDetailActive.this,CustomActivity.class);
                    startActivityForResult(intent,REQUEST_CODE_EMPLOYEE_NO);
                }
            });
            imageButtonLeaderNo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent=new Intent(PdfDetailActive.this,CustomActivity.class);
                    startActivityForResult(intent,REQUEST_CODE_LEADER_NO);
                }
            });
        }else{
            setContentView(R.layout.activity_pdf_detail);
        }
//        txtPDFtitle = (TextView) findViewById(R.id.txtPDFtitle);
        btnPDFclosed = (Button) findViewById(R.id.btnPDFclosed);
        txtEmployeeNo = (EditText) findViewById(R.id.txtEmployeeNo);
        txtLeaderNo = (EditText) findViewById(R.id.txtLeaderNo);
        btnSign = (Button) findViewById(R.id.btnSign);
        btnSerach = (Button) findViewById(R.id.btnSerach);
        wvPDF = (WebView) findViewById(R.id.wvPDF);



        Intent intent = getIntent();
        pdfTile = intent.getStringExtra("pdfTitle");
        pdfUrlBase = intent.getStringExtra("pdfUrlBase");

//        pdfUrl = intent.getStringExtra("pdfUrl").replace("mfcsharepointp1", "mfcsharepointp1.mflex.com.cn").replace("mfcprodftp", "mfcprodftp.mflex.com.cn");
        pdfUrl = intent.getStringExtra("pdfUrl");
        if(StringUtils.indexOf(pdfUrl,"mflex.com.cn")==-1){
            pdfUrl = intent.getStringExtra("pdfUrl").replace("mfcsharepointp1", "mfcsharepointp1.mflex.com.cn").replace("mfcprodftp", "mfcprodftp.mflex.com.cn");
        }
        webServiceUrl = intent.getStringExtra("webServiceUrl");
        docName = intent.getStringExtra("docName");
        docNumber = intent.getStringExtra("docNumber");
        docVersion = intent.getStringExtra("docVersion");
//        txtPDFtitle.setText(pdfTile);



        //加载PDF
        wvPDF.getSettings().setAllowFileAccess(true);
        wvPDF.getSettings().setJavaScriptEnabled(true);
        wvPDF.getSettings().setAllowContentAccess(true);
        wvPDF.getSettings().setAllowUniversalAccessFromFileURLs(true);
        wvPDF.getSettings().setAllowFileAccessFromFileURLs(true);
        wvPDF.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        wvPDF.getSettings().setBuiltInZoomControls(true);
        wvPDF.getSettings().setSupportZoom(true);
        wvPDF.getSettings().setDisplayZoomControls(false);
//        String pdfUrl1 = "";
//        try {
//             pdfUrl1 = URLEncoder.encode("http://mfcsharepointp1/mfcdcc/DocumentFiles/B/B02%20流程单图纸%20%20Drawing/1093723-00-D/1093723-00-D-LR%20SKETCH1.pdf","UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        String loadUrl = String.format("%s?pdfurl=%s",pdfUrlBase,pdfUrl);
//        String a = "http://localhost:2496/Default.aspx?pdfurl=";
//        loadUrl = "http://localhost:2496/Default.aspx?pdfurl=http://mfcsharepointp1/mfcdcc/DocumentFiles/B/B02%20流程单图纸%20%20Drawing/1093723-00-D/1093723-00-D-LR%20SKETCH1.pdf";
//        String result = "";
//        try {
//            result = URLEncoder.encode(loadUrl,"UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }

//        try {
//            result = new String(loadUrl.getBytes("iso8859-1"),"UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        try{
            wvPDF.loadUrl(loadUrl);
//            wvPDF.loadUrl("http://MFCPRODFTP.MFLEX.COM.CN/UploadedFiles/GX/FLEX/B工程文件/CBM11624_020-A SKETCH1.pdf");
        }catch(Exception e){
            e.printStackTrace();
        }

        btnPDFclosed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        btnSerach.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PdfDetailActive.this, SignQueryActivity.class);
                intent.putExtra("webServiceUrl", webServiceUrl);
//                intent.putExtra("pdfUrl", wiList.get(position).getIdentifier());
//                intent.putExtra("pdfTitle", wiList.get(position).getProduct());

                startActivity(intent);
            }
        });

        btnSign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtils.isEmpty(txtEmployeeNo.getText().toString())) {
                    SmileDialog dialog = new SmileDialogBuilder(PdfDetailActive.this, SmileDialogType.ERROR)
                            .setContentText("Employee ID is empty!")
                            .setTitleText("Error message")
                            .build();
                    return;
                }
                if (StringUtils.isEmpty(txtLeaderNo.getText().toString())) {
                    SmileDialog dialog = new SmileDialogBuilder(PdfDetailActive.this, SmileDialogType.ERROR)
                            .setContentText("Leader ID is empty!")
                            .setTitleText("Error message")
                            .build();
                    return;
                }
                request();
            }
        });
    }

    private void request() {
        final Dialog bean = DialogUIUtils.showLoading(PdfDetailActive.this, "In the signature, please wait a moment...", false, false, false, false).show();
        SimpleArrayMap<String, Object> map = new SimpleArrayMap<>();
//        map.put("Documentname", txtDocName.getText().toString());
//        map.put("Documentnumber", txtDocNub.getText().toString());
//        map.put("Employeeid", txtEmployeeId.getText().toString());
//        map.put("StartTime", txtStartTime.getText().toString());
//        map.put("EndTime", txtEndTime.getText().toString());
        map.put("DocNumber", docNumber);
        map.put("DocName", docName);
        map.put("DocVersion", docVersion);
        map.put("EmployeeId", txtEmployeeNo.getText().toString());
        map.put("LeaderId", txtLeaderNo.getText().toString());
        WebServiceUtil.call(webServiceUrl, "DoSignName", map, new WebServiceUtil.ResponseCallBack() {
            @Override
            public void onSuccess(Object result) {
//                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
//                intent.putExtra("userName", txtUser.getText().toString());
//                intent.putExtra("userPassword", txtPwd.getText().toString());
//                intent.putExtra("webServiceUrl", url);
//
//                intent.putExtra("pdfUrl", pdfUrl);
//
//                startActivity(intent);
                if(Boolean.parseBoolean(result.toString())){
                    txtEmployeeNo.setText("");
                    txtLeaderNo.setText("");
                    //设置焦点
                    txtEmployeeNo.setFocusable(true);
                    txtEmployeeNo.setFocusableInTouchMode(true);
                    txtEmployeeNo.requestFocus();
                    DialogUIUtils.showToast("Signature successful！");
                }

                DialogUIUtils.dismiss(bean);
            }

            @Override
            public void onError(String e) {

                DialogUIUtils.dismiss(bean);
                SmileDialog dialog = new SmileDialogBuilder(PdfDetailActive.this, SmileDialogType.ERROR)
                        .setContentText(e)
                        .setTitleText("Error message")
                        .build();
                dialog.show();
            }
        });
    }

    // 扫码界面回调方法
    @Override
    protected  void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode,resultCode,data);
        switch(requestCode) {
            case REQUEST_CODE_EMPLOYEE_NO:
                if(!StringUtils.isEmpty(CameraScan.parseScanResult(data))){
                    txtEmployeeNo.setText(CameraScan.parseScanResult(data));
                }
                break;
            case REQUEST_CODE_LEADER_NO:
                if(!StringUtils.isEmpty(CameraScan.parseScanResult(data))){
                    txtLeaderNo.setText(CameraScan.parseScanResult(data));
                }
                break;

        }
    }
}
